package com.xl.base.web;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import net.sf.json.JSONObject;

import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.servlet.ModelAndView;

import com.xl.base.entity.Operator;
import com.xl.core.util.HtmlUtil;
import com.xl.core.util.SessionLocalUtils;
import com.xl.core.util.prop.SysConfig;

public class BaseController {

	public final static String SUCCESS = "success";

	public final static String MSG = "msg";

	public final static String DATA = "data";

	public final static String LOGOUT_FLAG = "logoutFlag";

	protected HttpServletRequest request;
	protected HttpServletResponse response;

	/**
	 * 预处理数据
	 * 
	 * @param request
	 * @param response
	 */
	@ModelAttribute
	public void init(HttpServletRequest request, HttpServletResponse response) {
		// 设置请求
		this.request = request;
		this.response = response;
	}

	/**
	 * 所有ActionMap 统一从这里获取
	 * 
	 * @return
	 */
	public Map<String, Object> getRootMap(HttpServletRequest request) {
		Map<String, Object> rootMap = new HashMap<String, Object>();
		// 添加url到 Map中
		rootMap.put("baseUrl", SysConfig.baseUrl);

		Enumeration<String> enm = request.getParameterNames();
		while (enm != null && enm.hasMoreElements()) {
			String key = enm.nextElement().toString();
			/*String value = request.getParameter(key);
			 
			if("GET".equals(request.getMethod())){//前台encodeURIComponent('我们');转码后到后台还是ISO-8859-1，所以还需要转码  
                try {  
					value = URLDecoder.decode(value, "UTF-8");
				} catch (UnsupportedEncodingException e) {
					e.printStackTrace();
				}  
              } */
			rootMap.put(key,  request.getParameter(key));
		}

		// 获取当前操作用户
		Operator operator = SessionLocalUtils.getOperator();
		if (operator != null) {
			rootMap.put("operator", operator);
		}
		return rootMap;
	}

	/**
	 * 将Post流传入的json参数转化为对象
	 * 
	 * @param classType
	 * @return
	 * @throws IOException
	 */
	public <T> Object getJsonParams(Class<T> classType) throws IOException {
		// 读取请求内容
		BufferedReader br = new BufferedReader(new InputStreamReader(
				request.getInputStream()));
		String line = null;
		StringBuilder sb = new StringBuilder();
		while ((line = br.readLine()) != null) {
			sb.append(line);
		}
		@SuppressWarnings("unchecked")
		Map<String,Object> map=JSONObject.fromObject(URLDecoder.decode(sb.toString(), "utf-8"));
		Map<String,Object> map_=new HashMap<String, Object>();
		for (String key : map.keySet()) {
			 if(!"".equals(map.get(key))){
				 map_.put(key, map.get(key));
			 }
	    }
		return JSONObject.toBean(JSONObject.fromObject(map_),classType);
	}

	/**
	 * 跳转view
	 * 
	 * @param viewName
	 * @param context
	 * @return
	 */
	public ModelAndView forword(String viewName, Map context) {
		return new ModelAndView(viewName, context);
	}

	/**
	 * 重定向到新的页面
	 * 
	 * @param request
	 * @param response
	 * @param url
	 * @return
	 * @throws IOException
	 */
	public void sendRedirect(HttpServletRequest request,
			HttpServletResponse response, String url) throws IOException {

		String basePath = request.getScheme() + "://" + request.getServerName()
				+ ":" + request.getServerPort() + request.getContextPath();
		response.sendRedirect(basePath + url);
	}

	/**
	 * 
	 * 返回bootstrap数据
	 * 
	 */
	public void sendListData(HttpServletResponse response, int total,
			Object rows) {
		Map<String, Object> result = new HashMap<String, Object>();
		result.put("total", total);
		result.put("rows", rows);
		HtmlUtil.writerJson(response, result);
	}

	/**
	 * 
	 * 提示成功信息
	 * 
	 * @param message
	 * 
	 */
	public void sendSuccessMessage(HttpServletResponse response, String message) {
		Map<String, Object> result = new HashMap<String, Object>();
		result.put(SUCCESS, true);
		result.put(MSG, message);
		HtmlUtil.writerJson(response, result);
	}

	/**
	 * 
	 * 提示失败信息
	 * 
	 * @param message
	 * 
	 */
	public void sendFailureMessage(HttpServletResponse response, String message) {
		Map<String, Object> result = new HashMap<String, Object>();
		result.put(SUCCESS, false);
		result.put(MSG, message);
		HtmlUtil.writerJson(response, result);
	}
}
